package cc.yugu.yhdw.webserver.service.hdw;

import cc.yugu.yhdw.common.constant.ConstEnum;
import cc.yugu.yhdw.common.domain.hdw.Cabinet;
import cc.yugu.yhdw.common.domain.hdw.ExchangePriceSetting;
import cc.yugu.yhdw.common.entity.AreaCache;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.common.entity.tree.Node;
import cc.yugu.yhdw.common.entity.tree.NodeModel;
import cc.yugu.yhdw.common.utils.GeoHashUtils;
import cc.yugu.yhdw.common.utils.YhdwUtils;
import cc.yugu.yhdw.webserver.biz.client.ClientBizUtils;
import cc.yugu.yhdw.webserver.config.AppConfig;
import cc.yugu.yhdw.webserver.persistence.basic.AgentMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.*;
import cc.yugu.yhdw.webserver.service.AbstractService;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 换电柜业务
 * 
 * @Date:Created in 2018/7/6 15:19
 * @Author:
 * @Modified By: zjn 2018/7/6 15:19
 */ 
@Service
public class CabinetService extends AbstractService {

    static Logger log = LoggerFactory.getLogger(CabinetService.class);

    @Autowired
    AreaCache areaCache;
    @Autowired
    CabinetMapper cabinetMapper;
    @Autowired
    CabinetPropertyMapper cabinetPropertyMapper;
    @Autowired
    AppConfig appConfig;
    @Autowired
    CabinetBoxMapper cabinetBoxMapper;
    @Autowired
    CabinetStrategyMapper cabinetStrategyMapper;
    @Autowired
    AgentMapper agentMapper;
    @Autowired
    SupplierMapper supplierMapper;
    @Autowired
    ExchangeAmountMoneyDivideMapper exchangeAmountMoneyDivideMapper;
    @Autowired
    ExchangePriceSettingMapper exchangePriceSettingMapper;
    /**
    * 查询换电柜信息是否存在
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/6  15:19
    */ 
    public ExtResult findUnique(String id) {
        //根据你逐渐查询，返回行数
        if (cabinetMapper.findUnique(id) == 0) {
            return ExtResult.successResult();
        } else {
            return ExtResult.failResult("终端编号重复");
        }
    }
    /**
    * 查询
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.hdw.Cabinet
    * @Author By: zjn 2018/7/6  15:22
    */ 
    public Cabinet find(String id) {
        Cabinet cabinet = cabinetMapper.find(id);
        if (cabinet != null) {
            /// 先改成findAgency方法试试   ?????????????????
            //ExchangePriceSetting exchangePriceSetting = exchangePriceSettingMapper.findAgency(cabinet.getPriceSettingId());
            ExchangePriceSetting exchangePriceSetting = exchangePriceSettingMapper.find(cabinet.getPriceSettingId());
            if (exchangePriceSetting != null) {
                cabinet.setPriceSettingName(exchangePriceSetting.getSettingName());
            }
            cabinet.setAgentName(agentMapper.find(cabinet.getAgentId()) != null ? agentMapper.find(cabinet.getAgentId()).getAgentName() : "");
            cabinet.setAgencyName(findAgency(cabinet.getAgencyId()) != null ? findAgency(cabinet.getAgencyId()).getAgencyName() : "");
            cabinet.setPowerSupplierName(supplierMapper.find(cabinet.getPowerSupplierId()) != null ? supplierMapper.find(cabinet.getPowerSupplierId()).getSupplierName() : "");
            cabinet.setCabinetSupplierName(supplierMapper.find(cabinet.getCabinetSupplierId()) != null ? supplierMapper.find(cabinet.getCabinetSupplierId()).getSupplierName() : "");
            cabinet.setStrategyName(cabinetStrategyMapper.find(cabinet.getStrategyId()) != null ? cabinetStrategyMapper.find(cabinet.getStrategyId()).getStrategyName() : "");
            cabinet.setDividePlanName(exchangeAmountMoneyDivideMapper.find(cabinet.getDividePlanId()) != null ? exchangeAmountMoneyDivideMapper.find(cabinet.getDividePlanId()).getPlanName() : "");
        }
        return (Cabinet) setAreaProperties(areaCache, cabinet);
    }
    /**
    * 分页查询
    * 
    * @Param: [search]
    * @Return: cc.yugu.yhdw.common.entity.pagination.Page
    * @Author By: zjn 2018/7/7  11:01
    */ 
    public Page findPage(Cabinet search) {
        Page page = search.buildPage();
        page.setTotalItems(cabinetMapper.findPageCount(search));
        search.setBeginIndex(page.getOffset());

        List<Cabinet> cabinetList = cabinetMapper.findPageResult(search);
        // 这种循环查询速度较慢，可通过sql语句外链接查询
//        for (Cabinet cabinet : cabinetList) {
//            cabinet.setAgencyName(findAgency(cabinet.getAgencyId()) != null ? findAgency(cabinet.getAgencyId()).getAgencyName() : "");
//            cabinet.setStrategyName(cabinetStrategyMapper.find(cabinet.getStrategyId()) != null ? cabinetStrategyMapper.find(cabinet.getStrategyId()).getStrategyName() : "");
//        }

        page.setResult(setAreaProperties(areaCache, cabinetList));
        return page;
    }
    /**
    * 插入
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:03
    */ 
    public ExtResult insert(Cabinet entity) {
        try {
            // 设置心跳
            entity.setNormalFlag(ConstEnum.Flag.TRUE.getValue());
            entity.setCreateTime(new Date());
            entity.setProvinceId(1006);
            entity.setCityId(1007);
            entity.setDistrictId(1013);
            entity.setOnlineFlag(ConstEnum.Flag.FALSE.getValue());
            entity.setTemperature((byte) 0);
            entity.setFullVolume(90);
            entity.setChargeNum(3);
            cabinetMapper.insert(entity);
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 更新
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:03
    */ 
    public ExtResult updateBasic(Cabinet entity) {
        try {
            Cabinet cabinet = cabinetMapper.find(entity.getId());
            // 根据主键更新
            cabinetMapper.updateBasic(entity);
            // 温度判断
            if (cabinet.getFst() != entity.getFst() || cabinet.getFot() != entity.getFot() || cabinet.getPt() != entity.getPt() || cabinet.getRpt() != entity.getRpt()) {
                // 温度更新
                ClientBizUtils.cabinetChanged(appConfig, entity);
            }
            // 满电电量与最大充点数
            if (cabinet.getFullVolume() != entity.getFullVolume() || cabinet.getChargeNum() != entity.getChargeNum()) {
                List<String> cabinetIds = new ArrayList<String>();
                cabinetIds.add(cabinet.getId());
                ClientBizUtils.noticeEquipment(appConfig, cabinetIds);
            }
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 查询使用日志
    * 
    * @Param: [date, id]
    * @Return: java.util.List<java.lang.String>
    * @Author By: zjn 2018/7/7  11:10
    */ 
    public List<String> findUsageLog(Date date, String id) {
        if (date == null) {
            date = new Date();
        }
        List<String> list = cabinetMapper.findUsageLog(date, id);
//        for (int i = 0; i < list.size(); i++) {
//            list.set(i, list.get(i).replace(",", "<br/>"));
//        }
        return list;
    }
    /**
    * 查询指定格式的创建时间
    * 
    * @Param: [id]
    * @Return: java.util.List<java.lang.String>
    * @Author By: zjn 2018/7/7  11:11
    */ 
    public List<String> findUsageLogCount(String id) {
        return cabinetMapper.findUsageLogCount(id);
    }
    /**
    * 更新地址
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:11
    */ 
    public ExtResult updateLocation(Cabinet entity) {
        try {
            if (StringUtils.isEmpty(entity.getGeoHash())) {
                entity.setGeoHash(GeoHashUtils.getGeoHashString(entity.getLng(), entity.getLat()));
            }
            // 根据主键更新地址
            cabinetMapper.updateLocation(entity);
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 更新图片路径
    *
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:13
    */
    public ExtResult updateImage(Cabinet entity) {
        try {
            cabinetMapper.updateImage(entity);
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 更新各种温度
    * 
    * @Param: [cabinetId, fst, fot, pt, rpt]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:14
    */ 
    public ExtResult updateTemperature(String[] cabinetId, byte fst, byte fot, byte pt, byte rpt) {
        try {
            cabinetMapper.updateTemperature(cabinetId, fst, fot, pt, rpt);
            for (String c : cabinetId) {
                Cabinet cabinet = cabinetMapper.find(c);
                ClientBizUtils.cabinetChanged(appConfig, cabinet);
            }

        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 删除
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:14
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult delete(String id) {
        try {
            cabinetPropertyMapper.deleteByCabinet(id);
            cabinetBoxMapper.deleteByCabinet(id);
            cabinetMapper.delete(id);
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 登陆的目录树
    * 
    * @Param: [search, dummy, stream]
    * @Return: void
    * @Author By: zjn 2018/7/7  11:15
    */ 
    public void tree(Cabinet search, String dummy, OutputStream stream) throws IOException {
        // 查询登陆者名称
        List<Cabinet> list = cabinetMapper.findByArea(search);
        List<Node<NodeModel>> roots = new ArrayList<Node<NodeModel>>();

        Node<NodeModel> root = null;

        if (StringUtils.isNotEmpty(dummy)) {
            NodeModel data = new NodeModel();
            root = new Node<NodeModel>(data);
            data.setId(0);
            data.setName(dummy);
            roots.add(root);
        }

        for (Cabinet terminal : list) {
            NodeModel nodeModel = new NodeModel();
            Node<NodeModel> node = new Node<NodeModel>(nodeModel);
            nodeModel.setId(terminal.getId());
            nodeModel.setName(terminal.getCabinetName());
            if (root != null) {
                root.addChild(node);
            }
        }

        ObjectMapper objectMapper = new ObjectMapper();
        JsonGenerator json = objectMapper.getJsonFactory().createJsonGenerator(stream, JsonEncoding.UTF8);
        json.writeStartArray();
        YhdwUtils.writeJson(roots, json);
        json.writeEndArray();
        json.flush();
        json.close();
    }

    /**
     * 柜机分布图查询电池信息展示
     * @Param []
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Double>>
     * @Author zxj 2018/8/28
     */
    public List<Map<String, Double>> findAll() {
        return cabinetMapper.findAllToMap();
    }
    
    
}
